package commands

import (
	"errors"
	"strconv"
	"strings"
	"time"

	"github.com/larspensjo/config"
	"github.com/urfave/cli"

	"../flags"
	"../utils"
)

// Task - publish task
func Task(config utils.Config) cli.Command {
	return cli.Command{
		Name:     "task",
		Usage:    "publish task",
		Category: "MANAGER COMMANDS",
		Flags: []cli.Flag{
			flags.Flags["path"],
			cli.StringFlag{
				Name:  "user, u",
				Value: "[no user]",
				Usage: "publish task to `USER`",
			},
			cli.StringFlag{
				Name:  "message, m",
				Value: "no message",
				Usage: "with `MESSAGE`",
			},
			cli.StringFlag{
				Name:  "name",
				Usage: "task `NAME`",
			},
		},
		Action: makeAction(config, taskAction),
	}
}

/*
	## master
	# 发布返工任务(in hotfixes/release)
	sgbm-cli task --name "task2" -m "TODO" [ -u [user] ] # --name 自动补充前缀

	## manager
	# 建立 feature(from dev)/hotfixes(from master) 分支的开发任务，并指派给某人（可选）
	# 发布返工任务(in feature)
	sgbm-cli task --name "task1" -m "TODO" [ -u [user] ] # --name 自动补充前缀
*/
func taskAction(conf utils.Config, git utils.Git, context *cli.Context) error {
	configResult, err := utils.LoadConfig(conf, git, "config")
	if err != nil {
		return err
	}
	var ownName, ownRole string
	ownName, err = configResult.String("session", conf.PcCode)
	if err != nil {
		return errors.New("Please login")
	}
	ownRole, err = configResult.String("user", ownName)
	if err != nil {
		return errors.New("Session Info Error")
	}
	if ("master" != ownRole) && ("manager" != ownRole) {
		return errors.New("Please login with master/manager")
	}

	var masterName, devName, head string
	masterName, err = configResult.String("global", "master")
	if err != nil {
		return err
	}
	devName, err = configResult.String("global", "dev")
	if err != nil {
		return err
	}
	head, err = git.ThisBranch()
	if err != nil {
		return err
	}
	// fmt.Println("----------------[masterName] " + masterName)
	// fmt.Println("----------------[devName] " + devName)
	// fmt.Println("----------------[head] " + head)

	var logResult *config.Config
	logResult, err = utils.LoadConfig(conf, git, "log")
	if err != nil {
		return err
	}
	var num int
	num, err = logResult.Int("common", "num")
	if err != nil {
		return err
	}

	var TYPE, ID, BRANCH string
	if head == masterName {
		TYPE = "hotfixes"
		num++
		ID = strconv.Itoa(num)
		BRANCH = TYPE + "--" + ID

		_, err = git.Execute(
			[]string{"pull", "--all"},
			[]string{"branch", BRANCH},
			[]string{"push", "-u", "origin", BRANCH},
		)
		if err != nil {
			return err
		}
	} else if head == devName {
		TYPE = "feature"
		num++
		ID = strconv.Itoa(num)
		BRANCH = TYPE + "--" + ID

		_, err = git.Execute(
			[]string{"pull", "--all"},
			[]string{"branch", BRANCH},
			[]string{"push", "-u", "origin", BRANCH},
		)
		if err != nil {
			return err
		}
	} else {
		temp := strings.Split(head, "--")
		TYPE = temp[0]
		ID = temp[1]
		BRANCH = head

		if ("manager" == ownRole) && ("feature" != TYPE) {
			return errors.New("Please login with master")
		}
	}

	time := time.Now().Unix()
	TIME := strconv.FormatInt(time, 10)
	WORKER := context.String("user")
	MESSAGE := context.String("message")
	NAME := context.String("name")

	return utils.AddConfig(conf, git, "log", func(c *config.Config) *config.Config {
		c.AddOption("common", "num", strconv.Itoa(num))

		TASK := "task-" + ID
		c.AddSection(TASK)
		c.AddOption(TASK, "name", NAME)
		c.AddOption(TASK, "message", MESSAGE)
		c.AddOption(TASK, "publisher", ownName)
		c.AddOption(TASK, "worker", WORKER)
		c.AddOption(TASK, "type", TYPE)
		c.AddOption(TASK, "create_time", TIME)
		c.AddOption(TASK, "branch", BRANCH)

		c.AddOption(TASK, "active", "true")

		c.RemoveOption(TASK, "finish_time")
		c.RemoveOption(TASK, "finish_user")
		return c
	})
}

/*
[task-ID]
name = NAME
message = MESSAGE
publisher = ownName
worker = WORKER
# TYPE = hotfixes/release/feature
type = TYPE
create_time = TIME
branch = BRANCH

active = true/false
# =false 不再显示

finish_time = [time]
finish_user = [no user]

# branch name => hotfixes/release/feature--ID
*/
